package com.ruoyi.pingan.fymodule.order.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.pingan.fymodule.order.entity.*;
import com.ruoyi.pingan.fymodule.order.mapper.SxoSafetySepAccRevokeMapper;
import com.ruoyi.pingan.fymodule.order.service.*;
import com.ruoyi.pingan.fymodule.thirdpa.model.dto.MemberTransactionRefundDto;
import com.ruoyi.pingan.fymodule.thirdpa.model.dto.ThirdFreezeRechargeCancelDto;
import com.ruoyi.pingan.fymodule.thirdpa.model.dto.TraFinalStatusQueryDto;
import com.ruoyi.pingan.fymodule.thirdpa.model.vo.TraFinalStatusQueryVo;
import com.ruoyi.pingan.fymodule.thirdpa.service.PaBondService;
import com.ruoyi.pingan.fymodule.thirdpa.service.PaOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 *
 * 平安分账订单分账撤退 业务层实现
 *
 * @author wangy
 * @since 2025-06-19
 */
@Slf4j
@Service
public class SxoSafetySepAccRevokeServiceImpl extends ServiceImpl<SxoSafetySepAccRevokeMapper, SxoSafetySepAccRevoke> implements ISxoSafetySepAccRevokeService {
    @Autowired
    private PaOrderService paOrderService;
    @Autowired
    private PaBondService paBondService;
    @Autowired
    private ISxoSafetyMemTranService sxoSafetyMemTranService;
    @Autowired
    private ISxoSafetySepAccRevokeDetailService sxoSafetySepAccRevokeDetailService;

    @Autowired
    private ISxoSafetySepAccService sxoSafetySepAccService;
    @Autowired
    private ISxoSafetySepAccDetailService sxoSafetySepAccDetailService;

    @Autowired
    private ISxoSafetyOrderService sxoSafetyOrderService;


    @Override
    public void execute6273_6272() {
        log.info("分账撤退状态查询；时间:{}", DateUtil.now());
        Date date = new Date();
        Date startTime = DateUtil.offsetDay(date, -1);
        //Date endTime = DateUtil.offsetMinute(date, -120);
        LambdaQueryWrapper<SxoSafetySepAccRevoke> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SxoSafetySepAccRevoke::getSepStatus, 1);
        queryWrapper.eq(SxoSafetySepAccRevoke::getStatus, 0);
        queryWrapper.ge(SxoSafetySepAccRevoke::getSepRevokeTime, DateUtil.format(startTime, "yyyy-MM-dd").concat(" 00:00:00"));
        queryWrapper.le(SxoSafetySepAccRevoke::getSepRevokeTime, DateUtil.now());
        queryWrapper.orderByAsc(SxoSafetySepAccRevoke::getId);
        List<SxoSafetySepAccRevoke> lists = this.list(queryWrapper);
        if (lists.isEmpty()) {
            log.info("分账撤退状态查询；时间:{};数量：{}", DateUtil.now(), 0);
            return;
        }
        List<String> ids = lists.stream().map(SxoSafetySepAccRevoke::getId).toList();
        LambdaQueryWrapper<SxoSafetySepAccRevokeDetail> detailQueryWrapper = new LambdaQueryWrapper<>();
        detailQueryWrapper.in(SxoSafetySepAccRevokeDetail::getSepAccRevokeId, ids);
        detailQueryWrapper.eq(SxoSafetySepAccRevokeDetail::getSepStatus, 1);
        List<SxoSafetySepAccRevokeDetail> detailLists = sxoSafetySepAccRevokeDetailService.list(detailQueryWrapper);

        List<SxoSafetySepAcc> accs = null;

        List<String> sepAccId = lists.stream().map(SxoSafetySepAccRevoke::getSepAccId).toList();
        if (!sepAccId.isEmpty()) {
            accs = sxoSafetySepAccService.listByIds(sepAccId);
        }
        for (SxoSafetySepAccRevoke sxoSafetySepAccRevoke : lists) {
            boolean isSubitude = revFreezeRecharge(sxoSafetySepAccRevoke, detailLists);
            if (isSubitude) {
                //撤销补贴
                revSubsidy(sxoSafetySepAccRevoke);
                //撤销冻结充值
                revFreezeRecharge(sxoSafetySepAccRevoke);

                SxoSafetySepAccRevoke updateRevoke = new SxoSafetySepAccRevoke();
                updateRevoke.setId(sxoSafetySepAccRevoke.getId());
                updateRevoke.setSepStatus(0);
                updateRevoke.setSepRevokeSuccTime(DateUtil.now());
                this.updateById(updateRevoke);

                if (accs != null) {
                    SxoSafetySepAcc acc = accs.stream().filter(o -> o.getId().equals(sxoSafetySepAccRevoke.getSepAccId())).findFirst().orElse(null);
                    if (acc != null) {
                        SxoSafetyOrder modO = new SxoSafetyOrder();
                        modO.setId(acc.getSafetyOrderId());
                        modO.setSepStatus(3);
                        modO.setSepSuccTime(DateUtil.now());
                        sxoSafetyOrderService.updateById(modO);

                        SxoSafetySepAcc modC = new SxoSafetySepAcc();
                        modC.setId(acc.getId());
                        modC.setSepStatus(2);
                        modC.setSepRevokeTime(DateUtil.now());
                        sxoSafetySepAccService.updateById(modC);
                    }
                }
            }
        }

        log.info("分账状态查询；时间:{}；数量：{}", DateUtil.now(), lists.size());
    }

    private boolean revFreezeRecharge(SxoSafetySepAccRevoke revoke, List<SxoSafetySepAccRevokeDetail> detailLists) {
        List<SxoSafetySepAccRevokeDetail> details = detailLists.stream().filter(detail -> detail.getSepAccRevokeId().equals(revoke.getId())).toList();
        boolean isSubitude = false;
        for (SxoSafetySepAccRevokeDetail detail : details) {
            if (StrUtil.isEmpty(detail.getJzbAcceptSeqNo())) {
                continue;
            }
            SxoSafetySepAccRevokeDetail revokeDetail = new SxoSafetySepAccRevokeDetail();
            revokeDetail.setId(detail.getId());
            try {
                //分账撤销成功且返回见证受理流水号
                TraFinalStatusQueryDto dto = new TraFinalStatusQueryDto();
                dto.setOldJzbAcceptSeqNo(detail.getJzbAcceptSeqNo());
                TraFinalStatusQueryVo vo = paOrderService.traFinalStatusQuery(dto);
                if (!"6272".equals(vo.getTranType())) {
                    continue;
                }
                //执行vo的存储
                //交易状态0-成功；1-失败；3-处理中
                if ("0".equals(vo.getTranStatus())) {
                    String tranDateStr = vo.getTranDate().concat(vo.getTranTime());
                    Date tranDate = DateUtil.parse(tranDateStr);
                    //分账撤销状态
                    revokeDetail.setSepStatus(0);
                    //分账撤销时间
                    revokeDetail.setSepRevokeSuccTime(DateUtil.format(tranDate, "yyyy-MM-dd HH:mm:ss"));
                    revokeDetail.setErrorMsg("");
                    //分账撤销总交易金额
                    boolean bo = sxoSafetySepAccRevokeDetailService.updateById(revokeDetail);
                    if (bo) {
                        isSubitude = true;
                    }
                }
                if ("1".equals(vo.getTranStatus())) {
                    //分账撤销状态
                    revokeDetail.setSepStatus(-1);
                    revokeDetail.setErrorMsg(vo.getTranDealStatusDesc());
                    sxoSafetySepAccRevokeDetailService.updateById(revokeDetail);
                    isSubitude = false;
                }
            } catch (Exception e) {
                isSubitude = false;
                revokeDetail.setSepStatus(-1);
                revokeDetail.setErrorMsg(e.getMessage());
                sxoSafetySepAccRevokeDetailService.updateById(revokeDetail);
                log.error("execute6273_6272分账状态查询异常；时间:{}；订单号：{};异常信息：{}", DateUtil.now(), detail.getId(), e.getMessage());
            }
        }
        return isSubitude;
    }

    private void revSubsidy(SxoSafetySepAccRevoke sxoSafetySepAccRevoke) {
        LambdaQueryWrapper<SxoSafetyMemTran> tranQueryWrapper = new LambdaQueryWrapper<>();
        tranQueryWrapper.eq(SxoSafetyMemTran::getOrderId, sxoSafetySepAccRevoke.getOrderId());
        tranQueryWrapper.eq(SxoSafetyMemTran::getStatus, 0);
        tranQueryWrapper.eq(SxoSafetyMemTran::getTranStatus, 0);
        List<SxoSafetyMemTran> tranList = sxoSafetyMemTranService.list(tranQueryWrapper);
        if (tranList.isEmpty()) {
            return;
        }
        SxoSafetyMemTran tran = tranList.get(0);
        MemberTransactionRefundDto dto = new MemberTransactionRefundDto();
        dto.setSafetyTranId(tran.getId());
        dto.setFunctionFlag("2");
        paBondService.memberTransactionRefund(dto);


        log.info("撤销补贴；时间:{}；订单号：{};会员交易ID：{}", DateUtil.now(), sxoSafetySepAccRevoke.getOrderId(), tran.getId());
    }

    private void revFreezeRecharge(SxoSafetySepAccRevoke sxoSafetySepAccRevoke) {
        ThirdFreezeRechargeCancelDto dto = new ThirdFreezeRechargeCancelDto();
        dto.setOrderId(sxoSafetySepAccRevoke.getOrderId());
        paOrderService.thirdFreezeRechargeCancel(dto);
        log.info("撤销冻结充值；时间:{}；订单号：{}", DateUtil.now(), sxoSafetySepAccRevoke.getOrderId());
    }

}